//! 单线程存储管理器
//! 
//! 参考 Redis 官方设计，采用单线程架构，去除所有锁机制，
//! 使用高性能 FxHashMap 替代标准 HashMap，提供极速存储服务。

use crate::error::{Result, StorageError};
use crate::storage::data_types::*;
use fxhash::FxHashMap;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tracing::{debug, info};

/// 单线程存储管理器
/// 
/// 设计原则：
/// - 无锁设计：所有操作在单线程中执行
/// - 简单高效：使用高性能 FxHashMap，无并发开销
/// - 类型安全：保持原有的类型系统和错误处理
#[derive(Debug)]
pub struct SingleThreadStorage {
    /// 数据存储 - 使用高性能 FxHashMap，无锁
    data: FxHashMap<String, Box<dyn DataType>>,
    /// TTL 存储 - 记录每个 key 的过期时间
    ttl_data: FxHashMap<String, SystemTime>,
    /// 统计信息
    total_operations: u64,
    total_keys_created: u64,
    total_keys_deleted: u64,
}

impl SingleThreadStorage {
    /// 创建新的单线程存储实例
    pub fn new() -> Self {
        info!("Creating new high-performance single-thread storage engine (FxHash)");
        Self {
            data: FxHashMap::default(),
            ttl_data: FxHashMap::default(),
            total_operations: 0,
            total_keys_created: 0,
            total_keys_deleted: 0,
        }
    }

    /// 获取存储的 key 数量
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// 检查存储是否为空
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// 清空所有数据
    pub fn clear(&mut self) {
        let key_count = self.data.len();
        self.data.clear();
        self.ttl_data.clear();
        self.total_keys_deleted += key_count as u64;
        info!("Storage cleared, {} keys removed", key_count);
    }

    /// 检查 key 是否存在且未过期
    pub fn exists(&mut self, key: &str) -> bool {
        self.total_operations += 1;
        
        if !self.data.contains_key(key) {
            return false;
        }

        if self.is_expired(key) {
            self.cleanup_expired_key(key);
            return false;
        }

        true
    }

    /// 删除 key
    pub fn del(&mut self, key: &str) -> bool {
        self.total_operations += 1;
        
        let existed = self.data.remove(key).is_some();
        if existed {
            self.ttl_data.remove(key);
            self.total_keys_deleted += 1;
            debug!("Key '{}' deleted", key);
        }
        existed
    }

    /// 获取 key 的数据类型
    pub fn get_type(&self, key: &str) -> Option<String> {
        self.data.get(key).map(|data_type| data_type.type_name().to_string())
    }

    /// 获取所有 keys
    pub fn keys(&self) -> Vec<String> {
        self.data.keys().cloned().collect()
    }

    /// 获取 key 的内存使用量
    pub fn memory_usage(&self, key: &str) -> Option<usize> {
        self.data.get(key).map(|data_type| data_type.memory_usage())
    }

    /// 获取总内存使用量
    pub fn total_memory_usage(&self) -> usize {
        self.data.values().map(|data_type| data_type.memory_usage()).sum()
    }

    // === TTL 操作 ===

    /// 设置 key 的过期时间（秒）
    pub fn expire(&mut self, key: &str, seconds: u64) -> bool {
        if self.data.contains_key(key) {
            let expire_time = SystemTime::now() + Duration::from_secs(seconds);
            self.ttl_data.insert(key.to_string(), expire_time);
            debug!("Set expiration for key '{}' in {} seconds", key, seconds);
            true
        } else {
            false
        }
    }

    /// 设置 key 的过期时间戳
    pub fn expire_at(&mut self, key: &str, timestamp: u64) -> bool {
        if self.data.contains_key(key) {
            let expire_time = UNIX_EPOCH + Duration::from_secs(timestamp);
            self.ttl_data.insert(key.to_string(), expire_time);
            debug!("Set expiration for key '{}' at timestamp {}", key, timestamp);
            true
        } else {
            false
        }
    }

    /// 移除 key 的过期设置
    pub fn persist(&mut self, key: &str) -> bool {
        self.ttl_data.remove(key).is_some()
    }

    /// 获取 key 的剩余生存时间（秒）
    pub fn ttl(&mut self, key: &str) -> i64 {
        if !self.data.contains_key(key) {
            return -2; // Key 不存在
        }

        if let Some(expire_time) = self.ttl_data.get(key) {
            match expire_time.duration_since(SystemTime::now()) {
                Ok(duration) => duration.as_secs() as i64,
                Err(_) => {
                    // 已过期
                    self.cleanup_expired_key(key);
                    -2
                }
            }
        } else {
            -1 // Key 存在但无过期时间
        }
    }

    /// 获取 key 的剩余生存时间（毫秒）
    pub fn pttl(&mut self, key: &str) -> i64 {
        if !self.data.contains_key(key) {
            return -2; // Key 不存在
        }

        if let Some(expire_time) = self.ttl_data.get(key) {
            match expire_time.duration_since(SystemTime::now()) {
                Ok(duration) => duration.as_millis() as i64,
                Err(_) => {
                    // 已过期
                    self.cleanup_expired_key(key);
                    -2
                }
            }
        } else {
            -1 // Key 存在但无过期时间
        }
    }

    // === String 操作 ===

    /// SET 命令 - 设置字符串值
    pub fn set(&mut self, key: String, value: String) -> Result<()> {
        self.total_operations += 1;
        
        let is_new_key = !self.data.contains_key(&key);
        let string_type = Box::new(StringType::new(value.clone()));
        self.data.insert(key.clone(), string_type);
        
        if is_new_key {
            self.total_keys_created += 1;
        }
        
        debug!("SET {} = '{}'", key, value);
        Ok(())
    }

    /// GET 命令 - 获取字符串值
    pub fn get(&mut self, key: &str) -> Result<Option<String>> {
        self.total_operations += 1;
        
        if self.is_expired(key) {
            self.cleanup_expired_key(key);
            return Ok(None);
        }

        match self.data.get(key) {
            Some(data_type) => {
                if let Some(string_type) = data_type.as_any().downcast_ref::<StringType>() {
                    Ok(Some(string_type.get().to_string()))
                } else {
                    Err(StorageError::TypeMismatch {
                        expected: "string".to_string(),
                        found: data_type.type_name().to_string(),
                    })
                }
            }
            None => Ok(None),
        }
    }

    /// INCR 命令 - 自增
    pub fn incr(&mut self, key: &str) -> Result<i64> {
        self.incr_by(key, 1)
    }

    /// INCRBY 命令 - 按指定数值自增
    pub fn incr_by(&mut self, key: &str, amount: i64) -> Result<i64> {
        self.total_operations += 1;
        
        match self.data.get_mut(key) {
            Some(data_type) => {
                if let Some(string_type) = data_type.as_any_mut().downcast_mut::<StringType>() {
                    string_type.increment(amount)
                } else {
                    Err(StorageError::TypeMismatch {
                        expected: "string".to_string(),
                        found: data_type.type_name().to_string(),
                    })
                }
            }
            None => {
                let string_type = Box::new(StringType::new(amount.to_string()));
                self.data.insert(key.to_string(), string_type);
                self.total_keys_created += 1;
                Ok(amount)
            }
        }
    }

    // === Hash 操作 ===

    /// HSET 命令 - 设置 hash 字段
    pub fn hset(&mut self, key: &str, field: String, value: String) -> Result<bool> {
        self.total_operations += 1;
        
        match self.data.get_mut(key) {
            Some(data_type) => {
                if let Some(hash_type) = data_type.as_any_mut().downcast_mut::<HashType>() {
                    hash_type.hset(field, value)
                } else {
                    Err(StorageError::TypeMismatch {
                        expected: "hash".to_string(),
                        found: data_type.type_name().to_string(),
                    })
                }
            }
            None => {
                let mut hash_type = HashType::new();
                let result = hash_type.hset(field, value)?;
                self.data.insert(key.to_string(), Box::new(hash_type));
                self.total_keys_created += 1;
                Ok(result)
            }
        }
    }

    /// HGET 命令 - 获取 hash 字段值
    pub fn hget(&self, key: &str, field: &str) -> Result<Option<String>> {
        match self.data.get(key) {
            Some(data_type) => {
                if let Some(hash_type) = data_type.as_any().downcast_ref::<HashType>() {
                    hash_type.hget(field)
                } else {
                    Err(StorageError::TypeMismatch {
                        expected: "hash".to_string(),
                        found: data_type.type_name().to_string(),
                    })
                }
            }
            None => Ok(None),
        }
    }

    /// HDEL 命令 - 删除 hash 字段
    pub fn hdel(&mut self, key: &str, field: &str) -> Result<bool> {
        self.total_operations += 1;
        
        match self.data.get_mut(key) {
            Some(data_type) => {
                if let Some(hash_type) = data_type.as_any_mut().downcast_mut::<HashType>() {
                    let deleted = hash_type.hdel(field)?;
                    
                    // 检查哈希表是否为空，如果为空则删除整个键
                    if deleted && hash_type.hlen()? == 0 {
                        self.data.remove(key);
                        self.ttl_data.remove(key);
                        self.total_keys_deleted += 1;
                        debug!("Hash key '{}' completely removed after deleting last field", key);
                    }
                    
                    Ok(deleted)
                } else {
                    Err(StorageError::TypeMismatch {
                        expected: "hash".to_string(),
                        found: data_type.type_name().to_string(),
                    })
                }
            }
            None => Ok(false),
        }
    }

    // === 内部辅助方法 ===

    /// 检查 key 是否已过期
    fn is_expired(&self, key: &str) -> bool {
        if let Some(expire_time) = self.ttl_data.get(key) {
            SystemTime::now() >= *expire_time
        } else {
            false
        }
    }

    /// 清理单个过期的 key
    fn cleanup_expired_key(&mut self, key: &str) {
        self.data.remove(key);
        self.ttl_data.remove(key);
        self.total_keys_deleted += 1;
        debug!("Cleaned up expired key: {}", key);
    }

    /// 清理所有过期的 keys
    pub fn cleanup_expired_keys(&mut self) -> usize {
        let now = SystemTime::now();
        let expired_keys: Vec<String> = self.ttl_data
            .iter()
            .filter(|(_, expire_time)| now >= **expire_time)
            .map(|(key, _)| key.clone())
            .collect();

        let count = expired_keys.len();
        for key in &expired_keys {
            self.data.remove(key);
            self.ttl_data.remove(key);
        }

        if count > 0 {
            self.total_keys_deleted += count as u64;
            info!("Cleaned up {} expired keys", count);
        }

        count
    }

    /// 获取统计信息
    pub fn get_stats(&self) -> StorageStats {
        StorageStats {
            total_keys: self.data.len(),
            total_operations: self.total_operations,
            total_keys_created: self.total_keys_created,
            total_keys_deleted: self.total_keys_deleted,
            total_memory_usage: self.total_memory_usage(),
            ttl_keys_count: self.ttl_data.len(),
        }
    }
}

impl Default for SingleThreadStorage {
    fn default() -> Self {
        Self::new()
    }
}

/// 存储统计信息
#[derive(Debug, Clone)]
pub struct StorageStats {
    pub total_keys: usize,
    pub total_operations: u64,
    pub total_keys_created: u64,
    pub total_keys_deleted: u64,
    pub total_memory_usage: usize,
    pub ttl_keys_count: usize,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_operations() {
        let mut storage = SingleThreadStorage::new();

        // SET/GET
        storage.set("key1".to_string(), "value1".to_string()).unwrap();
        assert_eq!(storage.get("key1").unwrap(), Some("value1".to_string()));

        // INCR
        assert_eq!(storage.incr("counter").unwrap(), 1);
        assert_eq!(storage.incr("counter").unwrap(), 2);

        // HSET/HGET
        assert!(storage.hset("hash1", "field1".to_string(), "hvalue1".to_string()).unwrap());
        assert_eq!(storage.hget("hash1", "field1").unwrap(), Some("hvalue1".to_string()));

        // EXISTS/DEL
        assert!(storage.exists("key1"));
        assert!(storage.del("key1"));
        assert!(!storage.exists("key1"));
    }

    #[test]
    fn test_ttl_operations() {
        let mut storage = SingleThreadStorage::new();

        storage.set("ttl_key".to_string(), "value".to_string()).unwrap();
        
        // 设置 10 秒过期
        assert!(storage.expire("ttl_key", 10));
        
        // 检查 TTL
        let ttl = storage.ttl("ttl_key");
        assert!(ttl > 0 && ttl <= 10);

        // 移除过期时间
        assert!(storage.persist("ttl_key"));
        assert_eq!(storage.ttl("ttl_key"), -1);
    }

    #[test]
    fn test_statistics() {
        let mut storage = SingleThreadStorage::new();

        let initial_stats = storage.get_stats();
        assert_eq!(initial_stats.total_keys, 0);
        assert_eq!(initial_stats.total_operations, 0);

        storage.set("key1".to_string(), "value1".to_string()).unwrap();
        storage.get("key1").unwrap();
        storage.incr("counter").unwrap();

        let final_stats = storage.get_stats();
        assert_eq!(final_stats.total_keys, 2);
        assert_eq!(final_stats.total_operations, 3);
        assert_eq!(final_stats.total_keys_created, 2);
    }

    #[test]
    fn test_performance_benchmark() {
        let mut storage = SingleThreadStorage::new();
        let start = std::time::Instant::now();

        // 执行 10000 个操作
        for i in 0..10000 {
            storage.set(format!("key_{i}"), format!("value_{i}")).unwrap();
            storage.get(&format!("key_{i}")).unwrap();
            storage.incr(&format!("counter_{i}")).unwrap();
        }

        let elapsed = start.elapsed();
        let ops_per_sec = 30000.0 / elapsed.as_secs_f64();
        
        // 单线程存储性能测试统计
        
        // 期望至少达到 100,000 OPS
        assert!(ops_per_sec > 100_000.0, "Performance too low: {ops_per_sec} OPS");
    }
}